<?php
/**
 * 精简节假日api
 * @copyright tool.bitefu.net
 * @auther xiaogg@sina.cn
 */
class dateapi {
    public $path='data/';//数据目录
    //获取一天的节假日情况
	public function getday($day){
	    $year=substr($day,0,4);
        $yeardata=$this->yeardate($year);        
        if($yeardata){
            $nowday=substr($day,4,4);$dayvalue=@$yeardata[$nowday];
            if(!empty($dayvalue) || is_numeric($dayvalue))$returndata= $dayvalue;
        }
        if(!is_numeric($returndata))$returndata=$this->checkwork($day);
        if(empty($returndata))$returndata=0;
        $return=array('status'=>1,'info'=>$returndata);
        return $return;
	}
    /**
     * 获取一天的节假日情况
     * @param $time 日期时间戳
     * @return int 1 工作日 2调休(工作日) 3周未 4假日
     */
    public function getday2($time){
        $day=date('Y-m-d',$time);$dayarr=explode('-',$day);$year=$dayarr[0];	    
        $yeardata=$this->yeardate($year);
        $returndata = '';
        if($yeardata){
            $nowday=$dayarr[1].$dayarr[2];
            if(is_numeric($yeardata[$nowday])){
                $returndata = $yeardata[$nowday]>0? 4:2;
            }
        }
        if(empty($returndata)){
            $checkholidy=$this->checkwork($day);
            $returndata =$checkholidy>0?3:1;
        }
        return $returndata;
	}
    //检查是否是周未
	public function checkwork($day){
	   $weak=date("N",strtotime($day));
       return in_array($weak,array(6,7))?1:0;
	}
    //检查是否为合法日期
    public function check($day){
        $return=array('status'=>0,'info'=>'');
        if(empty($day) || strlen($day)<4){$return['info']='日期参数不正确';return $return;}        
	    $day_time=strtotime($day);if(date('Ymd',$day_time)!=$day){$return['info']='日期格式错误';return $return;}
        $return['status']=1;
        return $return;
    }
    //获取一年的数据
    private function yeardate($year=''){
        if(empty($year))$year=date('Y');
        static $cache = array();if(!empty($cache[$year])){return $cache[$year];}
        $new_file=$this->path.$year.'_data.json';
        if(file_exists($new_file)){
            $cache[$year]=json_decode(file_get_contents($new_file),true);   //读取年数据文件并 json转化为数组
            return $cache[$year];
        }else{
            $url = 'https://gitee.com/web/holidays_api/raw/master/data/'.$year.'_data.json';
            $content = file_get_contents($url);
            if(!empty($content) && $jsondata = json_decode($content,true)){
                file_put_contents($new_file,json_encode($jsondata));//自动更新 需要目录有写入权限
            }
            return false;
        } 
    }
}
?>